//
//  HNurseAssessUnloadViewController.m
//  NursingManages
//
//  Created by Zhen Huang on 17/7/9.
//  Copyright © 2017年 huangzhen. All rights reserved.
//

#import "HNurseAssessUnloadViewController.h"
#import "InitDbTableQuality.h"
#import "Model_Hr_Ns_Inspect_New.h"
#import "HUploadBaseTableViewCell.h"
#import "HQc_deptModel.h"
#import "InitDbTable.h"
#import "Model_Hr_SatType.h"
#import "InitDbTableHSatisfaction.h"
#import "Model_Hr_Satisfaction.h"
#import "ModelToJson.h"
#import "UploadPubQuality.h"
#import "HCommon.h"
#import "HQc_standardModel.h"
#import "HNurseAssessDetailEditViewController.h"
@interface HNurseAssessUnloadViewController ()
<UITableViewDelegate,
UITableViewDataSource>
@property (nonatomic ,strong)NSMutableArray *dataArray;
@property (nonatomic ,strong)NSDictionary *paramDic;
@property (nonatomic ,strong)UITableView *tabelView;
@property (nonatomic ,strong)NSMutableArray *titleArray;
@property (nonatomic ,strong)NSMutableArray *rowOfSectionArray;
@property (nonatomic ,assign) NSInteger indexSection;
@property (nonatomic ,assign) NSInteger indexRow;
@property (nonatomic ,strong) NSIndexPath *indexPath;
@property (nonatomic ,assign) NSInteger typeTag;
@end

@implementation HNurseAssessUnloadViewController


- (instancetype)initWithParam:(NSDictionary *)paramDic typeTag:(NSInteger)typeTag
{
    if (self) {
        self.paramDic = paramDic;
        self.titleArray = [NSMutableArray new];
        self.rowOfSectionArray = [NSMutableArray new];
        self.typeTag = typeTag;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *execbtn = [[UIBarButtonItem alloc] initWithTitle:@"上传" style:UIBarButtonItemStylePlain target:self action:@selector(didUploadButttonClicked:)];
    self.navigationItem.rightBarButtonItem = execbtn;
    
    [self.view addSubview:self.tabelView];

    
    NSNotificationCenter * centerSuccess = [NSNotificationCenter defaultCenter];
    [centerSuccess addObserver:self selector:@selector(RefreshNoticeSuccess:) name:@"UploadSuccess" object:nil];
    

    
    if ([self.type isEqualToString:@"manyidu"]) {
        if (self.typeTag == 1) {
            self.dataArray = [[[InitDbTableHSatisfaction alloc]init]getHSatisfaUnUpload];
            [self GetDataHsatis];

        }else if (self.typeTag == 2){
            self.dataArray = [[[InitDbTableHSatisfaction alloc]init]getHSatisfaDidUpload];
            [self GetDataHsatis];

        }
    }else if ([self.type isEqualToString:@"guochengkaohe"]){
        if (self.typeTag == 1) {
            self.dataArray = [[[InitDbTableQuality alloc]init]GetMainTableWithAssessUpload_flag:0 typy_id:[self.paramDic objectForKey:@"TYPE_ID"] level_id:@"2"];
            [self GetData];
        }else if (self.typeTag == 2){
            self.dataArray = [[[InitDbTableQuality alloc]init]GetMainTableWithAssessUpload_flag:1 typy_id:[self.paramDic objectForKey:@"TYPE_ID"] level_id:@"2"];
            [self GetData];

        }

    }

}

-(void)didUploadButttonClicked:(UIButton *)sender
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"是否确定上传?"
                                                    message:nil
                                                   delegate:nil
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"确定", nil];
    [alert show];
    alert.tag = 200;
    alert.delegate = self;
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 200) {
        switch (buttonIndex) {
            case 0:{
                return;
            }
                break;
            case 1:{
                
                if ([self.type isEqualToString:@"manyidu"]) {
                    InitDbTableHSatisfaction *initd = [[InitDbTableHSatisfaction alloc]init];
                    NSMutableArray *array = [initd getHSatisFaction];
                    
                    NSString *jsonTextDetail = [ModelToJson toJSON:array options:NSJSONWritingPrettyPrinted error:nil];
                    UploadPubQuality *upload = [[UploadPubQuality alloc]init];
                    
                    [upload startUpload:jsonTextDetail block:^(NSDictionary *param) {
                        BOOL flag =  [[param valueForKey:@"flag"] boolValue];
                        if( flag ){
                            [HCommon popupSuccessMessage:[NSString stringWithFormat:@"%@",[param objectForKey:@"msg"]]];
                            [self updateUploadFlag];
                        }
                        
                    }];

                }
            }
                break;
            default:
                break;
        }
    }
        if (alertView.tag == 300) {
            switch (buttonIndex) {
                case 0:{
                    return;
                }
                    break;
                case 1:{
                    
                    if ([self.type isEqualToString:@"manyidu"]) {
                        NSMutableArray *array = self.rowOfSectionArray[self.indexSection];
                        Model_Hr_Satisfaction*model = array[self.indexRow];
                        [array removeObjectAtIndex:self.indexRow];
                        InitDbTableQuality *initd = [[InitDbTableQuality alloc]init];
                        [initd deleteTableWithHSaTableCode:model.TABLE_CODE];
                        [self.tabelView deleteRowsAtIndexPaths:[NSArray arrayWithObject:self.indexPath] withRowAnimation:UITableViewRowAnimationFade];
                    }else {
                        NSMutableArray *array = self.rowOfSectionArray[self.indexSection];
                        Model_Hr_Ns_Inspect_New *model = array[self.indexRow];
                        [array removeObjectAtIndex:self.indexRow];
                        InitDbTableQuality *initd = [[InitDbTableQuality alloc]init];
                        [initd deleteTableWithResult_id:model.RESULT_ID];
                        [self.tabelView deleteRowsAtIndexPaths:[NSArray arrayWithObject:self.indexPath] withRowAnimation:UITableViewRowAnimationFade];
                         
                    }

                }
                    break;
                default:
                    break;
            }
        }

}

#pragma 通知的事件,执行刷新(上传成功)

- (void)RefreshNoticeSuccess:(NSNotification *)sender
{
    if ([self.type isEqualToString:@"manyidu"]) {
        [self.dataArray removeAllObjects];
        [self.titleArray removeAllObjects];
        self.dataArray = [[[InitDbTableHSatisfaction alloc]init]getHSatisfaUnUpload];
        [self GetDataHsatis];
        [self.tabelView reloadData];

    }else if ([self.type isEqualToString:@"guochengkaohe"])
    {
        [self.dataArray removeAllObjects];
        [self.titleArray removeAllObjects];
        self.dataArray = [[[InitDbTableQuality alloc]init]GetMainTableWithAssessUpload_flag:0 typy_id:[self.paramDic objectForKey:@"TYPE_ID"] level_id:@"2"];
        [self GetData];
        [self.tabelView reloadData];

    }
}

- (UITableView *)tabelView
{
    if (!_tabelView) {
        _tabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-NavBarHeight - 50) style:UITableViewStylePlain];
        _tabelView.dataSource = self;
        _tabelView.delegate = self;
        [_tabelView registerClass:[HUploadBaseTableViewCell class] forCellReuseIdentifier:@"cell"];
        _tabelView.tableFooterView = [[UIView alloc]init];
    }
    return _tabelView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return  self.titleArray.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return self.titleArray[section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = self.rowOfSectionArray[section];
    return array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        HUploadBaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        NSArray *array = self.rowOfSectionArray[indexPath.section];
    if ([self.type isEqualToString:@"manyidu"]) {
        
        Model_Hr_Satisfaction *model = array[indexPath.row];
        InitDbTableQuality *initd = [[InitDbTableQuality alloc]init];
        Model_Hr_SatType *codeModel = [initd GetHSaNameWithCodeID:model.SAT_TYPE];
        InitDbTable *inTabel = [[InitDbTable alloc]init];
        self.indexSection = indexPath.section;
        self.indexRow = indexPath.row;
        self.indexPath = indexPath;
        cell.code_nameLabel.text = codeModel.TYPE_NAME?:@"";
        cell.check_dateLabel.text = [NSString stringWithFormat:@"%@",model.SURVEY_DATE];
        
        cell.score_label.text = [NSString stringWithFormat:@"得分:%.2f",model.ITEM_SCORE];

        cell.check_nameLabel.text = [NSString stringWithFormat:@"检查者:%@",model.MODIFIER];
        HQc_deptModel *Model =  [inTabel GetQc_deptWithDept_id:model.DEPT_CODE];
        cell.checkDepartLabel.text = [NSString stringWithFormat:@"%@",Model.DEPT_NAME?:@""  ];

    }else {
        Model_Hr_Ns_Inspect_New *model = array[indexPath.row];
        InitDbTableQuality *initd = [[InitDbTableQuality alloc]init];
        HQc_codeModel *codeModel = [initd GetCodeNameWithCodeID:model.CODE_ID];
        self.indexSection = indexPath.section;
        self.indexRow = indexPath.row;
        self.indexPath = indexPath;
        cell.code_nameLabel.text = codeModel.CODE_NAME?:@"";
        cell.check_dateLabel.text = [NSString stringWithFormat:@"%@",model.CHECK_DATE];
        if ([model.SCORE isEqualToString:@"0"]) {
            cell.score_label.text = [NSString stringWithFormat:@"得分:%@",model.RESUL];

        }else {
            cell.score_label.text = [NSString stringWithFormat:@"得分:%@",model.SCORE];
        }
        cell.check_nameLabel.text = [NSString stringWithFormat:@"检查者:%@",model.CHECKER_NAME];
        cell.checkDepartLabel.text = [NSString stringWithFormat:@"被考核者:%@",model.NURSE_NAME?:@""  ];

    }
        return cell;
        
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.type isEqualToString:@"guochengkaohe"]) {
        NSArray *array = self.rowOfSectionArray[indexPath.section];
        Model_Hr_Ns_Inspect_New *model = array[indexPath.row];
        InitDbTableQuality *initd = [[InitDbTableQuality alloc]init];
        HQc_codeModel *codeModel = [initd GetCodeNameWithCodeID:model.CODE_ID];
        HNurseAssessDetailEditViewController *vc = [[HNurseAssessDetailEditViewController alloc]initWithRootCode:codeModel typeTag:self.typeTag InspectModel:model];
        
        vc.title = @"操作过程考核";
        [self.navigationController pushViewController:vc animated:YES];
        
    }

}

#pragma mark 获取源数据

- (void)GetData
{
    
    //对数据根据时间排序,时间最新的在前面
    NSArray *sortArray = [self.dataArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        
        Model_Hr_Ns_Inspect_New  *Model1 = obj1;
        Model_Hr_Ns_Inspect_New *Model2 = obj2;
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        
        [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
        
        NSDate *date1= [dateFormatter dateFromString:Model1.CHECK_DATE];
        NSDate *date2= [dateFormatter dateFromString:Model2.CHECK_DATE];
        
        if (date1 == [date1 earlierDate: date2]) { //不使用intValue比较无效
            
            return NSOrderedDescending;//降序
            
        }else if (date1 == [date1 laterDate: date2]) {
            return NSOrderedAscending;//升序
            
        }else{
            return NSOrderedSame;//相等
        }
        
    }];
    
    NSMutableArray *array= [NSMutableArray arrayWithArray:sortArray];
    NSMutableArray *dateMutablearray = [NSMutableArray new];
    NSMutableArray *titleArray = [NSMutableArray new];
    for(int i = 0;i < array.count;i ++) {
        
        Model_Hr_Ns_Inspect_New*model = array[i];
        if (![titleArray containsObject:[model.CHECK_DATE substringToIndex:7]]) {
            [titleArray addObject:[model.CHECK_DATE substringToIndex:7]];
        }
        NSMutableArray*tempArray = [@[]mutableCopy];
        NSString *string = [model.CHECK_DATE substringToIndex:7];
        [tempArray addObject:model];
        
        for(int j = i+1;j < array.count;j ++) {
            
            Model_Hr_Ns_Inspect_New*model1 = array[j];
            NSString *jstring = [model1.CHECK_DATE substringToIndex:7];
            
            if([string isEqualToString:jstring]){
                
                [tempArray addObject:model1];
                
                
                [array removeObjectAtIndex:j];
                j -= 1;
                
            }
            
        }
        
        [dateMutablearray addObject:tempArray];

        
    }
    self.rowOfSectionArray = dateMutablearray;
    self.titleArray = titleArray;
    
}

#pragma mark 获取源数据

- (void)GetDataHsatis
{
    
    //对数据根据时间排序,时间最新的在前面
    NSArray *sortArray = [self.dataArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        
        Model_Hr_Satisfaction  *Model1 = obj1;
        Model_Hr_Satisfaction *Model2 = obj2;
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        
        [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
        
        NSDate *date1= [dateFormatter dateFromString:Model1.SURVEY_DATE];
        NSDate *date2= [dateFormatter dateFromString:Model2.SURVEY_DATE];
        
        if (date1 == [date1 earlierDate: date2]) { //不使用intValue比较无效
            
            return NSOrderedDescending;//降序
            
        }else if (date1 == [date1 laterDate: date2]) {
            return NSOrderedAscending;//升序
            
        }else{
            return NSOrderedSame;//相等
        }
        
    }];
    
    NSMutableArray *array= [NSMutableArray arrayWithArray:sortArray];
    NSMutableArray *dateMutablearray = [NSMutableArray new];
    NSMutableArray *titleArray = [NSMutableArray new];
    for(int i = 0;i < array.count;i ++) {
        Model_Hr_Satisfaction*model = array[i];
        if (![titleArray containsObject:[model.SURVEY_DATE substringToIndex:7]]) {
            [titleArray addObject:[model.SURVEY_DATE substringToIndex:7]];
        }
        NSMutableArray*tempArray = [@[]mutableCopy];
        NSString *string = [model.SURVEY_DATE substringToIndex:7];
        [tempArray addObject:model];
        
        for(int j = i+1;j < array.count;j ++) {
            
            Model_Hr_Satisfaction*model1 = array[j];
            NSString *jstring = [model1.SURVEY_DATE substringToIndex:7];
            
            if([string isEqualToString:jstring]){
                
                [tempArray addObject:model1];
                
                
                [array removeObjectAtIndex:j];
                j -= 1;
                
            }
            
        }
        
        [dateMutablearray addObject:tempArray];
        
        
    }
    self.rowOfSectionArray = dateMutablearray;
    self.titleArray = titleArray;
    
}


-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"是否确定删除?"
                                                        message:nil
                                                       delegate:nil
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"确定", nil];
        [alert show];
        alert.tag = 300;
        alert.delegate = self;
        self.indexSection = indexPath.section;
        self.indexRow = indexPath.row;
        self.indexPath = indexPath;
        
        
    }
}
- (void)updateUploadFlag
{
    if (self.rowOfSectionArray.count > 0 ) {
        NSMutableArray *array = self.rowOfSectionArray[self.indexSection];
        Model_Hr_Satisfaction *model = array[self.indexRow];
        InitDbTableQuality *initd = [[InitDbTableQuality alloc]init];
        [initd UpdateTableWithHSaTableCode:model.TABLE_CODE];
        
    }else {
        [HCommon popupErrorMessage:@"无需上传的数据"];
    }
}
- (void)updateCaozuoUploadFlag
{
    if (self.rowOfSectionArray.count > 0 ) {
        NSMutableArray *array = self.rowOfSectionArray[self.indexSection];
        Model_Hr_Ns_Inspect_New * model = array[self.indexRow];
        InitDbTableQuality *initd = [[InitDbTableQuality alloc]init];
        [initd UpdateTableWithResult_id:model.RESULT_ID];
        
    }else {
        [HCommon popupSuccessMessage:@"无需上传的数据"];
    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
